﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using DAL.SystemManagement;
using System.Security.Cryptography;
using Common;

namespace Service
{
    public class UserMangementService : IUserMangementService
    {
        private const int PBKDF2_ITERATIONS = 1000;

        private const int SALT_BYTE_SIZE = 16;

        private const int HASH_BYTE_SIZE = 16;

        public async Task<IEnumerable<User>> GetAllUserByGroup(User user)
        {
            return await UserManagementDAL.GetAllUserByGroup(user);    
        }

        public async Task<IEnumerable<string>> QueryUserIndustry()
        {
            return await UserManagementDAL.QueryUserIndustry();
        }

        public bool Login(string userId, string password)
        {
            string passwordHashInDB = UserManagementDAL.GetPasswordHash(userId);

            string[] passwordParts = passwordHashInDB.Split(':');

            if (passwordParts.Length != 3)
            {
                return false;
            }

            byte[] passwordBytes = pbkdf2(password, passwordParts[1].HexStringToByte(), PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
          
            string passworldBase64 = Convert.ToBase64String(passwordBytes);

            byte[] passwordInDBBytes = passwordParts[2].HexStringToByte().JavaBytesToCSharpBytes();
            string passworldInDBBase64 = Convert.ToBase64String(passwordInDBBytes);

            return passworldBase64 == passworldInDBBase64;
        }

        private byte[] pbkdf2(string password, byte[] salt, int iterations, int bytes)
        {
            var rfc2898 = new Rfc2898DeriveBytes(password, salt, iterations);
            byte[] key = rfc2898.GetBytes(bytes);
            return key;
        }
    }
}
